package be.novelfaces.component.util.js;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.faces.context.FacesContext;

import org.apache.commons.lang.StringUtils;

public class JavaSriptConstructorWriterBuilder {

	private static final String QUOTE = "\"";
	private String namespace;
	private String constructor;
	private List<String> parameters = new ArrayList<String>();
	private JavaScriptWriter javaScriptWriter;
	
	public JavaSriptConstructorWriterBuilder(JavaScriptWriter javaScriptWriter) {
		this.javaScriptWriter = javaScriptWriter;
	}
	
	public JavaSriptConstructorWriterBuilder() {
		this(null);
	}

	public JavaScriptWriter writeConstructor() throws IOException {
		FacesContext.getCurrentInstance().getResponseWriter()
				.write(buildConstructor());
		return javaScriptWriter;
	}

	public JavaSriptConstructorWriterBuilder withNamespace(String namespace) {
		this.namespace = namespace;
		return this;
	}

	public JavaSriptConstructorWriterBuilder withConstructor(String constructor) {
		this.constructor = constructor;
		return this;
	}

	public JavaSriptConstructorWriterBuilder withParameter(String parameter) {
		this.parameters.add(parameter);
		return this;
	}
	
	public JavaSriptConstructorWriterBuilder withStringParameter(String parameter) {
		this.parameters.add(QUOTE + parameter + QUOTE);
		return this;
	}

	private String buildConstructor() {
		return "new " + buildNamespace() + constructor + "("
				+ buildParameters() + ");";
	}

	private String buildParameters() {
		if (parameters.isEmpty()) {
			return "";
		}
		StringBuilder builder = new StringBuilder();
		boolean first = true;
		for (String parameter : parameters) {
			if (!first) {
				builder.append(", ");
			}
			builder.append(parameter);
			first = false;
		}
		return builder.toString();
	}

	private String buildNamespace() {
		if (StringUtils.isBlank(namespace)) {
			return "";
		}
		return namespace + ".";
	}

}
